package com.shigen.file.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shigen.file.common.Common.MySql;
import com.shigen.file.common.Common.Pattern;
import com.shigen.file.emuns.YesNoEnum;
import com.shigen.file.entity.Project;
import com.shigen.file.entity.ProjectData;
import com.shigen.file.entity.UserInfo;
import com.shigen.file.exception.BusinessException;
import com.shigen.file.mapper.ProjectMapper;
import com.shigen.file.req.ProjectRequest.Create;
import com.shigen.file.req.ProjectRequest.QueryByName;
import com.shigen.file.res.ProjectResponse.PageResponse;
import com.shigen.file.service.IProjectDataService;
import com.shigen.file.service.IProjectService;
import com.shigen.file.service.IUserInfoService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 问卷收集表 服务实现类
 * </p>
 *
 * @author shigen.fu
 * @since 2022-06-04
 */
@Service
@Slf4j
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {

  @Resource
  private IUserInfoService userInfoService;
  @Resource
  private IProjectDataService projectDataService;


  @Override
  public IPage<PageResponse> queryByName(QueryByName queryByName) {
    Page<Project> page = new Page<>(queryByName.getPagenum(), queryByName.getPagesize());

    Wrapper<Project> projectQueryWrapper = Wrappers.<Project>lambdaQuery()
        .select(
            Project::getAutoId,
            Project::getProjId,
            Project::getProjName,
            Project::getBeginTime,
            Project::getEndTime,
            Project::getTitle,
            Project::getDescribe,
            Project::getWriteOnce
        )
        .like(StrUtil.isNotEmpty(queryByName.getName()), Project::getProjName, queryByName.getName())
        .orderByDesc(Project::getCreateTime)
        .eq(Project::getIsDel, 0);
    Page<Project> projectPage = getBaseMapper().selectPage(page, projectQueryWrapper);
    List<Project> records = projectPage.getRecords();

    Page<PageResponse> pageResponsePage = new Page<>(projectPage.getCurrent(), projectPage.getSize(), projectPage.getTotal());
    List<PageResponse> responses = new ArrayList<>(records.size());
    records.forEach(project -> responses.add(
        new PageResponse().setAutoId(project.getAutoId())
            .setProjId(project.getProjId())
            .setProjName(project.getProjName())
            .setBeginTime(DateUtil.formatDateTime(project.getBeginTime()))
            .setEndTime(DateUtil.formatDateTime(project.getEndTime()))
            .setTitle(project.getTitle())
            .setDescribe(project.getDescribe())
            .setWriteOnce(YesNoEnum.getDesc(project.getWriteOnce()))
    ));
    pageResponsePage.setRecords(responses);
    return pageResponsePage;
  }

  @Override
  public int createProject(Create create) {
    String callbackUrl = create.getCallbackUrl();
    if (StrUtil.isNotEmpty(callbackUrl) && !ReUtil.isMatch(Pattern.URL_PATTERN, callbackUrl)) {
      throw new BusinessException("提交的表单数据提交后跳转地址格式不正确");
    }

    UserInfo curUserInfo = userInfoService.getCurUserInfo();
    return getBaseMapper().insert(new Project()
        .setProjId(IdUtil.simpleUUID())
        .setProjName(create.getProjName())
        .setConfig(create.getConfig())
        .setBeginTime(DateUtil.parseDateTime(create.getBeginTime()))
        .setEndTime(DateUtil.parseDateTime(create.getEndTime()))
        .setTitle(create.getTitle())
        .setDescribe(create.getDescribe())
        .setList(create.getList())
        .setWriteOnce(create.isWriteOnce() ? 1 : 0)
        .setIsStop(0)
        .setCreateUserId(Long.valueOf(curUserInfo.getUserId()))
        .setCreateUserName(curUserInfo.getCreateUserName())
        .setIsDel(0)
        .setUpdateTime(new Date())
        .setCreateTime(new Date())
        .setCallbackUrl(callbackUrl)
    );
  }

  @Override
  public Project getProjectById(String id) {
    if (StrUtil.isEmpty(id)) {
      throw new BusinessException("表单id不能为空");
    }
    return lambdaQuery().eq(Project::getProjId, id).eq(Project::getIsDel, 0).one();
  }

  @Override
  public int changeProjectStatus(String projId, Boolean status) {
    return lambdaUpdate().eq(StrUtil.isNotEmpty(projId), Project::getProjId, projId)
        .set(Project::getIsStop, status).update() ? 1 : 0;
  }

  @Override
  public void downloadData(String projId, Boolean withAdditionInfo, HttpServletResponse response) {
    Project project = this.getProjectById(projId);
    if (project == null) {
      throw new BusinessException("该表单不存在");
    }
    IPage<ProjectData> page = new Page<>(0, MySql.MAX_PAGE_SIZE);
    try {
      EasyExcel.write(response.getOutputStream()).sheet().doWrite(projectDataService.getProjectData(projId, withAdditionInfo, page).getRecords());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
